package com.zch.house.service.impl;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zch.house.dao.RentDao;
import com.zch.house.entity.Rent;
import com.zch.house.service.RentService;
import com.zch.house.util.XmlSession;

public class RentServiceImpl extends XmlSession implements RentService {
	private final int PAGE_SIZE = 20;

	@Override
	public List<Rent> getAllRentByPage(String name, String phone, Date startDate, Date endDate, int pageIndex) {
		// 使用map集合来存放参数
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		map.put("phone", phone);
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		int firstRow = (pageIndex - 1) * PAGE_SIZE + 1;
		int lastRow = pageIndex * PAGE_SIZE;
		map.put("firstRow", firstRow);
		map.put("lastRow", lastRow);
		
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RentDao dao = session.getMapper(RentDao.class);
		//调用dao层方法
		List<Rent> list = dao.getAllRent(map);
		//提交事务并关闭session
		closeSession();
		return list;
	}

	@Override
	public int getTotalCount(String name, String phone, Date startDate, Date endDate) {
		// 使用map集合来存放参数
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		map.put("phone", phone);
		map.put("startDate", startDate);
		map.put("endDate", endDate);

		//加载配置文件
		initSession();
		//获得mapper的代理类
		RentDao dao = session.getMapper(RentDao.class);
		// 调用dao层方法获得查询到的所有数据的个数
		int counts = dao.getTotalCount(map);
		//提交事务并关闭session
		closeSession();
		// 计算总页数
		int totalPages = counts % PAGE_SIZE == 0 ? counts / PAGE_SIZE : counts / PAGE_SIZE + 1;
		return totalPages;
	}

	@Override
	public Rent getRentById(int id) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RentDao dao = session.getMapper(RentDao.class);
		//调用dao层方法
		Rent rent = dao.getRenById(id);
		//提交事务并关闭session
		closeSession();
		return rent;
	}

	@Override
	public boolean addRent(Rent rent) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RentDao dao = session.getMapper(RentDao.class);
		//调用dao层方法
		boolean flag = dao.addRent(rent);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

	@Override
	public boolean deleteRent(int id) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RentDao dao = session.getMapper(RentDao.class);
		//调用dao层方法
		boolean flag = dao.deleteRent(id);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

	@Override
	public boolean updateRent(Rent rent) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RentDao dao = session.getMapper(RentDao.class);
		//调用dao层方法
		boolean flag = dao.updateRent(rent);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

}
